package com.cn.dlr.zk.案例1;

import org.apache.zookeeper.*;

/**
 * @author: dlr
 * @data: 2019/8/8 22:30
 * @desc: 服务器 (服务器集群(3台,注册到zk集群),zk动态感知服务器的上下线,在通过客户端获取上下线信息)
 */
public class ProjectServer {
    //连接地址
    private static final String connectString = "192.168.10.20:2181,192.168.10.30:2181,192.168.10.40:2181";
    //session 会话
    private static final int sessionTimeout = 2000;
    ZooKeeper zooKeeper;
    public static void main(String[] args) throws Exception{
        ProjectServer server=new ProjectServer();
        //连接zk服务器
        server.getZkConeection();
        //向zk注册本服务
        server.registZk(args[0]);
        //执行业务逻辑(让进程不要死掉,就回代表一个服务器开启状态)
        server.doWork();
    }

    //连接zk服务器
    private void getZkConeection() throws Exception {
        zooKeeper= new ZooKeeper(connectString, sessionTimeout, new Watcher(){
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }

    //向zk注册本服务
    private void registZk(String str) throws Exception{
        //临时有序节点
        String path = zooKeeper.create("/servers/server", str.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(path);
    }

    private void doWork() throws Exception{
        Thread.sleep(Long.MAX_VALUE);
    }

}
